<?php
/**
 * 正常 返回一个分润数组
 * 错误 返回false
 */
require_once 'streamconfig.php';
class Tourismstream extends Streamconfig
{
    //订单分润表别名
    protected $price_profit;
    protected $bargaining;
    protected $user;
    protected $tourism_goods_attr;
    protected $tourism_profit_rate;
    protected $user_credit;
    protected $user_credit_log;

    //需要返回的参数
    public $orderPayTotal;    //议价时的订单支付。
    public $calculate_method; //是否议价
    public $supply_price = 0; //供应价
    public $shop_price = 0;   //销售价

    //分润必要参数
    protected $sellerUid; //购买者uid
    protected $parentUid; //购买者上级UID
    protected $bitTrade;  //购买者用户的类型
    protected $productId; //产品的id
    protected $bitWan;    //1:在线支付；2：到付
    protected $number;    //当前数量
    protected $supplyUid; //供应商uid
    protected $rateId;    //分润模版编号

    public function __construct($tables = array())
    {
        parent::__construct();
        if (count($tables) > 0) {
            $this->initialize($tables);
        }
    }

    /**
     * 初始化数据
     * @param $tables
     */
    public function initialize($tables)
    {
        foreach ($tables as $alias=>$table) {
            $this->CI->load->model($table.'_model', $table);
            $this->$alias = $this->CI->$table; //给表别名赋值
        }
    }

    public function tourism($parameter = [])
    {
        if (!$this->validateChkValue($parameter)) {
            $this->setError('参数不正确！');
            return false;
        }
        $result = $this->bargaining->findByArray(['seller_uid' => $this->sellerUid, 'product_id' => $this->productId]);
        if ($result->num_rows() > 0) { /** 如果议价了。*/
            $bargainingRow = $result->row();
            $this->supply_price = $bargainingRow->supply_price;
            $this->shop_price   = $bargainingRow->shop_price;
            $orderProfit = $this->tourismBargainingProfit($bargainingRow);
            $this->calculate_method = 2;
        } else {
            /** 如果购买者上级用户是供应商对应分销商，那么该产品的利润全部归该供应商对应分销商所有*/
            $providerResult = $this->user_related_self->findOne(['provider_uid' => $this->supplyUid, 'flag' => 1], 'id, provider_uid, reseller_uid, poundage');
            if ((($this->bitTrade)&UTID_CUSTOMER) && ($providerResult->num_rows() > 0) && ($providerResult->row(0)->reseller_uid == $this->parentUid)) {
                $this->calculate_method = 3;//上下级
                $providerRow = $providerResult->row(0);
                $orderProfit = $this->providerProfit($providerRow);
            } else { /** 走正常分润流程。*/
                $orderProfit = $this->tourismProfit();
            }
        }

        $error = $this->getError();
        if (!empty($error)) {
            return false;
        }
        return $orderProfit;
    }

    /**
     * 验证参数。
     * @param unknown $parameter
     * @return boolean
     */
    private function validateChkValue($parameter)
    {
        $sysParameter = array('sellerUid', 'parentUid', 'bitTrade','productId', 'number', 'bitWan','supplyUid', 'rateId');
        foreach ($sysParameter as $kv) {
            if (!isset($parameter[$kv])) {
                return false;
            }
            $this->$kv = $parameter[$kv];
        }
        $this->calculate_method = 1;
        $this->orderPayTotal = 0;
        return true;
    }

    /**
     * 比较两个数组的值，将数组中的金额相加并取交集。
     * @param $orderProfitAdult
     * @param $orderProfitChild
     * @return array
     */
    private function dealwithOrderProfitData($orderProfitAdult, $orderProfitChild)
    {
        $orderProfit = array();
        foreach ($orderProfitAdult as $key=>$value) {
            if (array_key_exists($key, $orderProfitChild)) {
                $orderProfitAdult[$key] = $value;
                $orderProfitAdult[$key]['account'] += $orderProfitChild[$key]['account'];
                unset($orderProfitChild[$key]);
            }
            $orderProfit[] = $value;
        }
        $orderProfit = array_merge($orderProfitAdult, $orderProfitChild);
        return $orderProfit;
    }

    /**
     * 获取订单分润表所需要的数据
     * @return void|Ambigous <void, unknown>
     */
    public function tourismProfit()
    {
        $product = $this->tourism_goods_attr->findByAttrId($this->productId);
        if ($product->num_rows() <= 0) {
            $this->setError('产品信息错误！');
            return false;
        }
        $product = $product->row();
        $this->supply_price = $product->supply_price;
        $this->shop_price   = $product->shop_price;

        //没有议价，验证是否有单独设置分润，有直接分润，没有验证是否有设置分润模版，没有按照标准模版分润（1）
        $result = $this->price_profit->findGoodsProfit(['status' => 1, 'goods_attr_id' => $this->productId]);
        if ($result->num_rows() <= 0) { //如果单独设置分润，则走分润模版
            $profitRate = $this->tourism_profit_rate->findOne(['rate_id' => ['in' => [$this->rateId, 1]]], '*', 'uid DESC');
            if ($profitRate->num_rows() <= 0) {
                $this->setError('数据设置有误~');
            }
            $profitPrice = $this->getProfitRateList($profitRate->row(0));
        } else {
            $profitPrice = $result->result();
        }
        return $this->getOrderProfitData($profitPrice, $product);
    }

    /**
     * 按照指定默认模版或默认模版进行分钱
     * @param $profitPrice
     * @return mixed
     */
    public function getProfitRateList($profitPrice)
    {
        $profit = [];
        $diffPrice = $this->shop_price - $this->supply_price;
        $exceptLastTotal = 0;
        $bitUser = [UTID_PROVIDER, UTID_PROSECOND, UTID_PURCHASER, UTID_BEIZHU, UTID_MANAGER_L1, UTID_MANAGER_L2, UTID_GROWTH, UTID_SELLER];
        foreach ($bitUser as $key => $type) {
            $profit[$key]['goods_attr_id'] = $this->productId;
            $profit[$key]['bit_trade']     = $type;
            $profit[$key]['type_id']       = $type;
            $profit[$key]['status']        = 1; //1,代表分润。2，代表议价
            if ($type == UTID_PROVIDER) {
                $profit[$key]['uid']       = $profitPrice->uid ? $profitPrice->uid : $this->supplyUid;
                $profit[$key]['amount']    = $this->supply_price;
            }
            if ($type == UTID_PROSECOND) {
                $profit[$key]['uid']       = $profitPrice->prosecond_id;
                $profit[$key]['amount']    = $profitPrice->prosecond > 0 ? bcmul($diffPrice, ($profitPrice->prosecond/100), 2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_PURCHASER) {
                $profit[$key]['uid']       = $profitPrice->purchaser_id;
                $profit[$key]['amount']    = $profitPrice->purchaser > 0 ? bcmul($diffPrice, ($profitPrice->purchaser/100), 2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_BEIZHU) {
                $profit[$key]['uid']       = UTID_BEIZHU;
                $profit[$key]['amount']    = $profitPrice->beizhu > 0 ? bcmul($diffPrice, ($profitPrice->beizhu/100),2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_MANAGER_L1) {
                $profit[$key]['uid']       = $profitPrice->manager_l1_id;
                $profit[$key]['amount']    = $profitPrice->manager_l1 > 0 ? bcmul($diffPrice, ($profitPrice->manager_l1/100), 2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_MANAGER_L2) {
                $profit[$key]['uid']       = $profitPrice->manager_l2_id;
                $profit[$key]['amount']    = $profitPrice->manager_l2 > 0 ? bcmul($diffPrice, ($profitPrice->manager_l2/100), 2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_GROWTH) {
                $profit[$key]['uid']       = $profitPrice->growth_id;
                $profit[$key]['amount']    = $profitPrice->growth > 0 ? bcmul($diffPrice, ($profitPrice->growth/100), 2) : 0;
                $exceptLastTotal          += $profit[$key]['amount'];
            }
            if ($type == UTID_SELLER) {
                $profit[$key]['uid']       = $profitPrice->seller_id;
                $profit[$key]['amount']    = $diffPrice - $exceptLastTotal; //$profitPrice->seller > 0 ? ($diffPrice * $profitPrice->seller) : 0;
            }
        }
        return json_decode(json_encode($profit));
    }

    /**
     * 获取供应对应分销商利润的分成
     * @param $providerRow
     * @return array|bool
     */
    public function providerProfit($providerRow)
    {
        $result = $this->provider_poundage_profit->providerPoundageProfit($providerRow->id);
        $product = $this->tourism_goods_attr->findByAttrId($this->productId);
        if ($product->num_rows() <= 0){
            $this->setError('产品信息错误！');
            return false;
        }
        $product = $product->row();
        $this->supply_price = $product->supply_price;
        $this->shop_price = $product->shop_price;
        return $this->getProviderProfitData($result,$product,$providerRow->reseller_uid,$providerRow->poundage);
    }

    /**
     * 如果设置利润手续费分成信息正式分钱
     * @param $poundageProfit
     * @param $product
     * @param $reseller_uid
     * @param $poundage
     * @return array
     */
    public function getProviderProfitData($poundageProfit,$product,$reseller_uid,$poundage)
    {
        $orderProfit   = array();
        $payee = array();
        $this->orderPayTotal = bcmul($product->shop_price,$this->number,2);
        $profit = bcmul($product->shop_price-$product->supply_price,$this->number,2);
        //供应商的钱先提前分
        $payee['uid'] = $this->supplyUid;
        $payee['account'] = bcmul($product->supply_price,$this->number,2);
        $payee['account_type'] = ACCOUNT_TYPE_CARRY;
        $payee['as']           = 1;
        $payee['bit_trade']    = UTID_PROVIDER;
        array_push($orderProfit, $payee);
    
        if ($poundageProfit->num_rows() > 0) {
            foreach($poundageProfit->result() as $key=>$value){ //手续费分给指定的人
                $payee['uid'] = $value->uid;
                $payee['account'] = bcmul($profit,($poundage/100)*(($value->poundage)/100),2);
                $payee['account_type'] = ACCOUNT_TYPE_CARRY;
                $payee['as']           = 1;
                $payee['bit_trade']    = $value->bit_trade;
                if(!empty($payee)){
                    array_push($orderProfit, $payee);
                }
            }
        } else { //利润钱全部给着想总部
            $payee['uid'] = 16;
            $payee['account'] =  bcmul($profit,($poundage/100),2);
            $payee['account_type'] = ACCOUNT_TYPE_CARRY;
            $payee['as']           = 1;
            $payee['bit_trade']    = 16;
            array_push($orderProfit, $payee);
        }
    
        //供应商对应分销商的钱先提前分
        $payee['uid']          = $reseller_uid;
        $payee['account']      = bcmul($profit, (1-($poundage/100)),2);
        $payee['account_type'] = ACCOUNT_TYPE_CARRY;
        $payee['as']           = 1;
        $payee['bit_trade']    = UTID_SELLER;
        array_push($orderProfit, $payee);
        return $orderProfit;
    }

    public function getOrderProfitData($profitObj, $product)
    {
        $targets = $this->getTargets($this->sellerUid);
        if (empty($targets)) {
            $this->setError('获取不到账户的上级用户');
            return false;
        }
        foreach ($profitObj as $key=>$value) {
            if ($value->bit_trade != UTID_PROVIDER && $value->bit_trade != UTID_PURCHASER && $value->uid == 0) { //如果用户类型不是“供货商”，也不是“采购商”
                $value->uid = $this->firstTarget($value->bit_trade, $targets);
            }
            $profitObj[$key] = $value;
        }
        return $this->orderProfitDetails($profitObj, $product);
    }

    private function orderProfitDetails($profitObj, $product)
    {
        if ($this->bitWan == 1) {//在线
            return $this->onlinePaymentProfit($profitObj, $product);
        } else if ($this->bitWan == 2) {
            return $this->arrivalPaymentProfit($profitObj, $product);
        }
    }

    /**
     * 在线支付
     * @param $profitObj
     * @param $product
     * @return array|bool
     */
    private function onlinePaymentProfit($profitObj, $product)
    {
        $orderProfit   = array();

        $salePrice     = 0; //销售价
        $providerPrice = 0; //供应价
        $reseller      = 0; //分销商利润(当前购买者)
        foreach ($profitObj as $key=>$value) {
            $payee = array();
            //购买者区别对待。//如果用户类型不同 并且 用户uid不相等
            switch ($value->bit_trade) {
                case UTID_PROVIDER://如果是供应商，获取供应价
                    $payee['uid']          = $value->uid;
                    $payee['account']      = $value->amount*$this->number;
                    $payee['account_type'] = ACCOUNT_TYPE_CARRY;
                    $payee['as']           = 1;
                    $payee['bit_trade']    = $value->type_id;
                    break;
                case UTID_PROSECOND: //二级供应商
                case UTID_PURCHASER: //采购商
                case UTID_BEIZHU:    //着想自己
                    $payee['uid']          = $value->uid;
                    $payee['account']      = $value->amount*$this->number;
                    $payee['account_type'] = ACCOUNT_TYPE_CARRY;
                    $payee['as']           = 1;
                    $payee['bit_trade']    = $value->type_id;
                    break;
                case UTID_MANAGER_L1://如果是购买者是分销商，也可能是发展商，也可能是一级或二级代理
                case UTID_MANAGER_L2:
                case UTID_GROWTH:
                case UTID_SELLER:
                    if ((int)$this->bitTrade&$value->bit_trade) {
                        $reseller += $value->amount*$this->number;
                    } else if ($value->uid != $this->sellerUid) {
                        $payee['uid']          = $value->uid;
                        $payee['account']      = $value->amount*$this->number;
                        $payee['account_type'] = ACCOUNT_TYPE_CARRY;
                        $payee['as']           = 1;
                        $payee['bit_trade']    = $value->type_id;
                    }
                    break;
                default:
                    $this->setError('用户('.$value->uid.')的类型（'.$value->bit_trade.'）有误');
                    break;
            }
            $salePrice += $value->amount*$this->number;
            if (!empty($payee)) {
                array_push($orderProfit, $payee);
            }
        }
        if (bccomp($product->shop_price*$this->number, $salePrice, 2)) {
            $this->setError('分润或产品设置有误。');
            return false;
        }
        $this->orderPayTotal += $salePrice - $reseller; //当前实际应支付金额 - 这个分销商所分的钱
        return $orderProfit;
    }

    /**
     * 到付 -- 供应商 要给我们钱
     * @param $profitObj
     * @param $product
     * @return array|bool
     */
    private function arrivalPaymentProfit($profitObj, $product)
    {
        $orderProfit   = array();
        $payee = array();
        $salePrice     = 0; //销售价总价
        foreach ($profitObj as $key=>$value) {
            //购买者区别对待。
            switch ($value->bit_trade) {
                case UTID_PROVIDER://如果是供应商，获取供应价
                    $payee['account'] = $product->shop_price - $product->supply_price;
                    $payee['as']      = 2;
                    break;
                case UTID_PROSECOND: //二级供应商
                case UTID_PURCHASER: //采购商
                case UTID_BEIZHU:    //着想自己
                case UTID_MANAGER_L1://如果是购买者是分销商，也可能是发展商，也可能是一级或二级代理
                case UTID_MANAGER_L2:
                case UTID_GROWTH:
                case UTID_SELLER:
                    $payee['account'] = $value->amount*$this->number;
                    $payee['as']      = 1;
                    $salePrice += $value->amount*$this->number;
                    break;
                default:
                    $this->setError('用户('.$value->uid.')的类型（'.$value->bit_trade.'）有误');
                    break;
            }
            $payee['bit_trade']    = $value->type_id;
            $payee['account_type'] = ACCOUNT_TYPE_MONTH;
            $payee['uid']          = $value->uid;

            if(!empty($payee)){
                array_push($orderProfit, $payee);
            }
        }
        //到付，供应商要返给我们利润钱
        if (bccomp(($product->shop_price - $product->supply_price)*$this->number, $salePrice)) {
            $this->setError('分润或产品设置有误。');
            return false;
        }
        $this->orderPayTotal = $salePrice; //当前实际应支付金额 - 这个分销商所分的钱
        return $orderProfit;
    }

    public function tourismBargainingProfit($bargainingRow)
    {
        $bargainingProfit = $this->price_profit->findGoodsProfit(array('status' => 2, 'goods_attr_id' => $bargainingRow->bargaining_id));
        if ($bargainingProfit->num_rows() <= 0) {
            //$this->setError('该产品议价了，但没有设置议价分润');
            $profitRate = $this->tourism_profit_rate->findOne(['rate_id' => ['in' => [$this->rateId, 1]]], '*', 'uid DESC');
            if ($profitRate->num_rows() <= 0) {
                $this->setError('数据设置有误~');
            }
            $bargainingProfit = $this->getProfitRateList($profitRate->row());
        } else {
            $bargainingProfit = $bargainingProfit->result();
        }
        if ($this->bitWan == '1') { //在线
            return $this->onlinePaymentBargaining($bargainingRow, $bargainingProfit);
        } elseif ($this->bitWan == '2') {
            return $this->arrivalPaymentBargaining($bargainingRow, $bargainingProfit);
        }
    }

    private function onlinePaymentBargaining($bargainingRow, $bargainingProfit)
    {
        $orderProfit = $this->getOrderProfitOnlinePayer($bargainingRow, $bargainingProfit);
        if ($bargainingRow->node == '1') { //系统结算
            $amountTotal = 0;
            switch ($bargainingRow->payer) {
                case '1' : //分销商付手续费
                    $amountTotal   = ($bargainingRow->supply_price + $bargainingRow->poundage + $bargainingRow->prosecond_profit)*$this->number;
                    break;
                case '2' : //供应商付手续费
                    $amountTotal   = ($bargainingRow->supply_price + $bargainingRow->prosecond_profit)*$this->number;
                    $orderProfit[$bargainingRow->provider_uid]['account'] = $orderProfit[$bargainingRow->provider_uid]['account'] - $bargainingRow->poundage * $this->number;
                    break;
                case '3' ://二级供应商付手续费
                    $amountTotal   = ($bargainingRow->supply_price + $bargainingRow->prosecond_profit)*$this->number;
                    $orderProfit[$bargainingRow->prosecond_id]['account'] = $orderProfit[$bargainingRow->prosecond_id]['account'] - $bargainingRow->poundage * $this->number;
                    break;
            }
            $this->orderPayTotal = $amountTotal + ($amountTotal * ($bargainingRow->bankpay/100));
        } else /*if ($bargainingRow->node == '2')*/ { //自主结算
            //自主结算，验证授信金额，记录授信额度账单
            $credit = $this->userCredit();
            if (!$credit) {
                return $credit;
            }
            $this->orderPayTotal = $bargainingRow->poundage * $this->number;
            if (empty($orderProfit)) {
                return true;
            }
        }
        return $orderProfit;
    }

    /**
     * 议价在线支付-减去指定的手续费
     * @param $bargainingRow
     * @param $bargainingProfit
     * @return mixed
     */
    private function getOrderProfitOnlinePayer($bargainingRow, $bargainingProfit)
    {
        $orderProfit = [];
        if ($bargainingRow->node == 1) { //系统结算
            $orderProfit[$bargainingRow->provider_uid]['uid']          = $bargainingRow->provider_uid;
            $orderProfit[$bargainingRow->provider_uid]['account']      = $bargainingRow->supply_price * $this->number;
            $orderProfit[$bargainingRow->provider_uid]['account_type'] = ACCOUNT_TYPE_CARRY;
            $orderProfit[$bargainingRow->provider_uid]['bit_trade']    = UTID_PROVIDER;
            $orderProfit[$bargainingRow->provider_uid]['as']           = 1;
        }
        //二级供应商
        if ($bargainingRow->prosecond_profit > 0 && $bargainingRow->prosecond_id) {
            $orderProfit[$bargainingRow->prosecond_id]['uid']          = $bargainingRow->prosecond_id;
            $orderProfit[$bargainingRow->prosecond_id]['account']      = $bargainingRow->prosecond_profit * $this->number;
            $orderProfit[$bargainingRow->prosecond_id]['account_type'] = ACCOUNT_TYPE_CARRY;
            $orderProfit[$bargainingRow->prosecond_id]['bit_trade']    = UTID_PROSECOND;
            $orderProfit[$bargainingRow->prosecond_id]['as']           = 1;
        }
        if (!empty($bargainingProfit)) {
            foreach ($bargainingProfit as $key=>$value) {
                $orderProfit[$value->uid]['uid']          = $value->uid;
                $orderProfit[$value->uid]['account']      = $value->amount * $this->number;
                $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_CARRY;
                $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                $orderProfit[$value->uid]['as']           = 1;
            }
        }
        return $orderProfit;
    }

    /**
     * 到付，不存在自主结算和系统结算。
     * 到付，我们就只收手续费分润钱，不存在收取银行利息
     * @param unknown $bargainingRow
     * @param unknown $bargainingProfit
     * @return Ambigous <number, multitype:multitype:number Ambigous <multitype:number, multitype:number string unknown NULL > >
     */
    private function arrivalPaymentBargaining($bargainingRow, $bargainingProfit)
    {
        $orderProfit = $this->providerPayTotalArrivalPayer($bargainingRow, $bargainingProfit);

        $poundage = $bargainingRow->poundage *  $this->number;
        switch ($bargainingRow->payer) {
            case '1' : //分销商付手续费,到付给供应商，还是供应商欠我们手续费的钱
                $orderProfit[$this->sellerUid]['account'] = $orderProfit[$this->sellerUid]['account'] - $poundage;
                break;
            case '2' : //供应商付手续费，是供应商付我们的钱
                $orderProfit[$bargainingRow->provider_uid]['account'] = ($bargainingRow->shop_price - $bargainingRow->supply_price) * $this->number - $poundage;
                break;
            case '3' ://二级供应商付手续费，是二级供应商欠我们钱，但是二级供应商的账户余额必须要大于这个钱。
                $orderProfit[$bargainingRow->prosecond_id]['account'] = $bargainingRow->prosecond_profit * $this->number - $poundage;
                break;
        }
        //这里是分销商(当前用户)要付给供应商多少钱？。
//        $this->orderPayTotal = $bargainingRow->poundage * $this->number;
        return $orderProfit;
    }

    /**
     * 供应商要给我们多少钱？
     * @param $bargainingRow
     * @param $bargainingProfit
     * @return mixed
     */
    public function providerPayTotalArrivalPayer($bargainingRow, $bargainingProfit)
    {
        $orderProfit[$bargainingRow->provider_uid]['uid']          = $bargainingRow->provider_uid;
        $orderProfit[$bargainingRow->provider_uid]['account']      = ($bargainingRow->shop_price - $bargainingRow->supply_price) * $this->number;
        $orderProfit[$bargainingRow->provider_uid]['account_type'] = ACCOUNT_TYPE_MONTH;
        $orderProfit[$bargainingRow->provider_uid]['bit_trade']    = UTID_PROVIDER;
        $orderProfit[$bargainingRow->provider_uid]['as']           = 2;
        //二级供应商
        if ($bargainingRow->prosecond_profit > 0 && $bargainingRow->prosecond_id) {
            $orderProfit[$bargainingRow->prosecond_id]['uid']          = $bargainingRow->prosecond_id;
            $orderProfit[$bargainingRow->prosecond_id]['account']      = $bargainingRow->prosecond_profit * $this->number;
            $orderProfit[$bargainingRow->prosecond_id]['account_type'] = ACCOUNT_TYPE_MONTH;
            $orderProfit[$bargainingRow->prosecond_id]['bit_trade']    = UTID_PROSECOND;
            $orderProfit[$bargainingRow->prosecond_id]['as']           = 1;
        }

        if (!empty($bargainingProfit)) {
            foreach ($bargainingProfit as $key=>$value) {
                $orderProfit[$value->uid]['uid']          = $value->uid;
                $orderProfit[$value->uid]['account']      = $value->amount * $this->number;
                $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_MONTH;
                $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                $orderProfit[$value->uid]['as']           = 1;
            }
        }

        $orderProfit[$this->sellerUid]['uid']          = $this->sellerUid;
        $orderProfit[$this->sellerUid]['account']      = ($bargainingRow->shop_price - $bargainingRow->prosecond_profit - $bargainingRow->supply_price)*$this->number;
        $orderProfit[$this->sellerUid]['account_type'] = ACCOUNT_TYPE_MONTH;
        $orderProfit[$this->sellerUid]['bit_trade']    = 4096;
        $orderProfit[$this->sellerUid]['as']           = 1;
        return $orderProfit;
    }

    //自主结算，验证授信金额，记录授信额度账单
    public function userCredit()
    {
        $result = $this->user_credit->findOne(['uid' => $this->sellerUid, 'provider_id' => $this->supplyUid]);
        if ($result->num_rows() > 0) {
            $credit = $result->row(0);
            $money  = $this->shop_price * $this->number;
            $amount = bccomp($credit->amount, $money, 2);
            if ($amount < 0) {
                $this->setError('授信金额不足~');
                return false;
            }
            $update = $this->user_credit->update(['amount' => $amount], ['uid' => $this->sellerUid, 'provider_id' => $this->supplyUid]);
            $lastId = $this->user_credit_log->insert(['credit_id' => $credit->id, 'type' => 1, 'money' => $money, 'note' => '消费授信额度', 'state' => 1, 'created_at' => date('Y-m-d H:i:s')]);
            if (!$update || !$lastId) {
                $this->setError('授信金额不足~');
                return false;
            }
        } else {
            $this->setError('自主结算需联系商家设置授信额度~');
            return false;
        }
        return true;
    }
}